package com.woniuxy.controller;

import com.woniuxy.common.LoadBalance;
import com.woniuxy.entity.Constants;
import com.woniuxy.entity.Order;
import com.woniuxy.entity.ResultVO;
import com.woniuxy.entity.User;
import com.woniuxy.service.IOrderService;
import org.omg.PortableInterceptor.USER_EXCEPTION;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * @author : mafan
 * @date : 2020-11-18 20:41
 **/
@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalance lb;
    /**
     * 以下的对象，用于服务发现
     */
    @Autowired
    private DiscoveryClient discoveryClient;
    /**
     * 轮询下标
     */
//    private int index = 0;
//    private int maxTime = 5;
//    private int times = 1;
//    //轮询算法
//    private ServiceInstance getServer( List<ServiceInstance> instances){
//        if (times<maxTime){
//            times++;
//        }else {
//            index++;
//            if (index>instances.size()-1){
//                index = 0;
//            }
//        }
//        ServiceInstance instance = instances.get(index);
//        return instance;
//    }

    /**
     * 下订单
     * @param pid    要购买的商品id
     * @param number 要购买的数量
     * @return
     */
    @PostMapping("create/{pid}/{number}")
    public ResultVO createOrder(@PathVariable Integer pid, @PathVariable Integer number) {
//        //获取product-service 服务集群
//        List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
//        //获取集群中的服务器节点
//        ServiceInstance instance = lb.getServer(instances);
//
//        String uri = instance.getUri().toString();



        Order order = new Order();
        // 根据pid查询product，这里就要发起远程调用了。
//        ResultVO resultVO = restTemplate.getForObject(uri+"/product/" + pid, ResultVO.class);
        ResultVO resultVO = restTemplate.getForObject("http://product-service/product/" + pid, ResultVO.class);
        if (resultVO.getStatus() == Constants.OPER_FAILURE) {
            return resultVO;
        }

        Map data = (Map) resultVO.getData();
        order.setPid(pid);
        order.setPname((String) data.get("pname"));
        order.setPrice((Double) data.get("price"));
        order.setNumber(number);

        //这是一个业务片段，所有把下订单的用户id写死
        order.setUid(1);
        order.setUsername("张无忌");

        // 检查库存是否充足
        Integer stock = (Integer) data.get("stock");
        if (stock < number) {
            return new ResultVO(Constants.OPER_FAILURE, "库存不足，剩余：" + stock + "，订单数量：" + number);
        }
        //  发起远程调用，进行扣减库存逻辑处理
//        resultVO = restTemplate.postForObject(uri+"/product/deductStock/" + pid + "/" + number, null, ResultVO.class);
        resultVO = restTemplate.postForObject("http://product-service/product/deductStock/" + pid + "/" + number, null, ResultVO.class);
        if (resultVO.getStatus() == Constants.OPER_FAILURE) {
            return new ResultVO(Constants.OPER_FAILURE, "扣减库存失败");
        }
        //存入订单
        ResultVO resultVO2;
        try {
            orderService.save(order);
//            resultVO2 = new ResultVO(Constants.OPER_SUCCESS, "本次请求的是"+uri+"下单成功", order);
            resultVO2 = new ResultVO(Constants.OPER_SUCCESS,"下单成功", order);
        } catch (Exception e) {
            e.printStackTrace();
            resultVO2 = new ResultVO(Constants.OPER_FAILURE, "下单失败",e.getMessage());
        }
        return resultVO2;
    }
    //restTemplate 如何发json数据
    @PostMapping("saveUser")
    public ResultVO saveUser(@RequestBody User user){
        ResultVO resultVO = restTemplate.postForObject("http://localhost:8071/user/save",user, ResultVO.class);

        return resultVO;
    }
}